package org.csu.myPetStore.web.servlet;

import org.csu.myPetStore.domain.Account;
import org.csu.myPetStore.domain.Product;
import org.csu.myPetStore.service.CatalogService;
import org.csu.myPetStore.service.LogcatService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Date;
import java.util.List;

public class SearchProductServlet extends HttpServlet {

    private String keyWord;
    private static final String PRODUCCT_SEARCH_VIEW = "/WEB-INF/jsp/catalog/SearchProducts.jsp";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        keyWord = req.getParameter("keyword");

        CatalogService service = new CatalogService();
        List<Product> productList = service.searchProductList(keyWord);

        HttpSession session = req.getSession();
        session.setAttribute("KeyProductList",productList);

        Account account = (Account) session.getAttribute("account");

        if(account != null){
            LogcatService logcatService = new LogcatService();

            java.util.Date date = new java.util.Date();
            Date datesql = new Date(date.getTime());
            logcatService.InsertLogCat(account.getUsername(),account.getUsername() + " Search " + keyWord + " at " + datesql.toString());

        }


        req.getRequestDispatcher(PRODUCCT_SEARCH_VIEW).forward(req,resp);
    }

}
